import Vue from 'vue'
import VueRouter from 'vue-router'
import Login from '@/page/login/Login'
import Register from '@/page/login/Register'
import Phone from './page/login/Phone';
import Home from '@/page/Home'
import Category from '@/page/Category'
import User from '@/page/User'

Vue.use(VueRouter)

const routes = [
  {
    path: '/',
    redirect: '/home'
  },
  {
    path: '/login',
    component: Login,
    name: 'login',
    meta: {
      title: '登录'
    }
  },
  {
    path: '/registe',
    component: Register,
    name: 'registe',
    meta: {
      title: '注册'
    }
  },
  {
    path: '/phone',
    component: Phone,
    name: 'phone',
    meta: {
      title: '手机登录'
    }
  },
  {
    path: '/home',
    component: () => import('./page/index'),
    children: [
      {
        path: '/home',
        component: Home,
        name: 'home'
      },
      {
        path: '/category',
        component: Category,
        name: 'category',
        meta: {
          auth: true // 设置当前路由需要校验   不需要校验的路由就不用写了
        }
      },
      {
        path: '/user',
        component: User,
        name: 'user',
        meta: {
          auth: true // 设置当前路由需要校验   不需要校验的路由就不用写了
        }
      }
    ]
  }
]

const router = new VueRouter({
  // mode: 'history',
  routes
})

router.beforeEach((to, from, next) => {
  if (to.matched.some(m => m.meta.auth)) {
    // 对路由进行验证
    if (localStorage.getItem('username') !== null) { // 已经登陆
      // 正常跳转到你设置好的页面
      next()
    } else {
      // 未登录则跳转到登陆界面，query:{ Rurl: to.fullPath}表示把当前路由信息传递过去方便登录后跳转回来；
      alert('您还没有登录，请先进行登录！')
      next({ path: '/login' })
    }
  } else {
    next()
  }
})

export default router
